package com.bigevent.service.impl;

import com.bigevent.mapper.UserMapper;
import com.bigevent.pojo.User;
import com.bigevent.service.UserService;
import com.bigevent.utils.Md5Util;
import com.bigevent.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Override
    public User findByUserName(String username) {
        User user = userMapper.findByUserName(username);
        return user;
    }

    @Override
    public void register(String username, String password) {
        // 加密
        String md5String = Md5Util.getMD5String(password);

        // 获取当前时间
        LocalDateTime date = LocalDateTime.now();
        // 保存
        userMapper.register(username,md5String,date);
    }

    @Override
    public void update(User user) {
        user.setUpdateTime(LocalDateTime.now());
        userMapper.update(user);
    }

    @Override
    public void updateUserPic(String userPic) {
        Map<String,Object> claims = ThreadLocalUtil.get();
        Integer id = (Integer) claims.get("id");
        LocalDateTime date = LocalDateTime.now();
        userMapper.updateUserPic(userPic,id,date);
    }

    @Override
    public void updateUserPwd(Map<String, String> params) {
        String oldPwd = params.get("old_pwd");
        String newPwd = params.get("new_pwd");
        Map<String,Object> claims = ThreadLocalUtil.get();
        String username = (String) claims.get("username");
        User user = userMapper.findByUserName(username);
        LocalDateTime date = LocalDateTime.now();
        if (user.getPassword().equals(Md5Util.getMD5String(oldPwd))){
            userMapper.updateUserPwd(Md5Util.getMD5String(newPwd),user.getId(),date);
        }else {
            throw new RuntimeException("旧密码错误");
        }
    }
}
